/**
 * 帖子发布相关函数
 * 
 * @author		布衣才子
 * @date		2012-10-10
 * @copyright	2012-2015 YeeYi.com 
 * @email		work.jerryliu@gmail.com
 * @QQ			394969553
 */


var httpCode = 0;
var uid = getLocalStorge('uid');
var picUploadHttp = "http://www.yeeyi.com/bbs/forum.php?mod=mobile&ac=upload&uid="+uid;
var apiHost = "http://www.yeeyi.com/bbs/forum.php?jsoncallback=?&s="+getTime()+"&mod=mobile";
var upload_image_url = '';
var b64 = new Base64();

var lat; //经度
var lon; //纬度


/**
 * 网络请求中转函数
 * 
 * @param {Object} url  请求的网络地址
 * @param {Object} callback  回调函数
 */
function xmlHttp(url,callback){
	if(url == ''){
		uexWindow.alert('参数错误','请求地址不能为空！','返回');
	}else{
		var platform = getLocalStorge('platform');
		url = url + "&pf="+platform;
		$.getJSON(url,callback);
	}
}

/**
 * 关闭窗口
 */
function closeWindow(){
	uexWindow.close(-1);
}

/**
 * 取消图片
 */
function picCancel(){
	$('.showpic').hide(2000);
	$('thumbPlace').html('');
}

/**
 * 选择或拍摄好照片后的响应函数
 * 
 * @param {Object} opCode
 * @param {Object} dataType
 * @param {Object} data
 */
function getReadyToUpload(opCode, dataType, data){
	upload_image_url = data;
	var thumbObj = $('.thumbPlace');
	var thumbHTML = '<div onclick="cancelPic(this)" class="docancel"><img src="css/images/cancel.png" class="cancelPic"><img class="thumbPic" src="'+data+'" /></div>';
	thumbObj.append(thumbHTML);
	$('.showpic').show();
	httpCode = httpCode + 1;
	showLoading("图片开始上传，请稍后……",0);
	uexUploaderMgr.createUploader(httpCode,picUploadHttp);
}

/**
 * 创建上传的管理对象
 * 
 * @param {Object} opCode
 * @param {Object} dataType
 * @param {Object} data
 */
function uexUploaderMgrCbCreateUploader(opCode,dataType,data){
	if(data == 0){
		uexUploaderMgr.uploadFile(opCode,upload_image_url,"Filedata","2");	
	}else{
        showLoading("上传失败……",1);
		removeErrorPic();
	}
}

/**
 * 图片上传过程的监控函数
 * 
 * @param {Object} opCode
 * @param {Object} fileSize
 * @param {Object} percent
 * @param {Object} serverReback
 * @param {Object} status
 */
function uexUploaderMgrStatusCb(opCode,fileSize,percent,serverReback,status){
	
	switch (status) {  
           case 0://正在上传
                 if(fileSize>2560000){
                     uexUploaderMgr.closeUploader(opCode);
                     showLoading('上传失败！您上传的图片大小为：'+parseInt(fileSize/1000)+'KB，超过2M的限制！',1);
					 removeErrorPic();
					 return false;
                  }else{
                      showLoading('已上传'+percent+'%',0);
                  }
                  break;
           case 1://上传完毕
                  if(serverReback.length > 3){
				  	  givePicAid(serverReback);
                      uexWindow.toast("0","5","图片上传成功…","2000");
					  showLoading('图片上传成功！',1);   
                  }else{
				  	  if(serverReback == '407'){
					  	 uexWindow.alert("未找到当前用户，请先登录!");
						 removeErrorPic();
					  }	
                      uexWindow.toast("0","5","图片上传失败…","2000");
					  showLoading('图片上传失败！',1);
					  removeErrorPic();
                  }
                  
				  uexUploaderMgr.closeUploader(opCode);
                  break;
           case 2:
                 uexWindow.alert("图片上传失败");
				 showLoading("图片上传失败……",1);
				 removeErrorPic();
                 uexUploaderMgr.closeUploader(opCode);
                 break;
        }    
}

/**
 * 发布新帖子
 */
function postNewThread(){
	
	uexWindow.toast("1","5","帖子正在发布…","0");
	var imgObj = $(".thumbPic");
	var allAid = '';
	var imgClass = '';
	//获取图片附件ID
	$.each(imgObj,function(index,name){
		imgClass = $(name).attr('title');
		if(allAid == ''){
			allAid = imgClass;
		}else{
			allAid = allAid + ',' + imgClass;
		}
	})
	
	var regionStr = $.trim($('#region').text());
	var subject = $.trim($('#subject').val());
	var message = $.trim($('#message').val());
	var ctype = $('#ctype').val();
	var fid = getLocalStorge('fid');
	var uid = getLocalStorge('uid');
	var username = getLocalStorge('username');
	var password = getLocalStorge('pwd');
	
	if(subject.length <= 2){
		uexWindow.closeToast();
		uexWindow.toast("0","5","提交失败，标题过短…","2000");
		return false;
	}
	
	if(message.length <= 2){
		uexWindow.closeToast();
		uexWindow.toast("0","5","提交失败，内容太短了些吧…","2000");
		return false;
	}
	
	
	if(!fid){
		uexWindow.closeToast();
		uexWindow.toast("0","5","提交失败，没有找到对应板块…","2000");
		return false;
	}
	
	
	if(!uid){
		uexWindow.closeToast();
		uexWindow.toast("0","5","提交失败，用户UID缺失…","2000");
		return false;
	}
	
	
	_subject = encodeURIComponent(b64.encode(subject));
	_message = encodeURIComponent(b64.encode(message));
	_ctype = encodeURIComponent(ctype);
	_region = encodeURIComponent(b64.encode(regionStr));
	_imgaid = encodeURIComponent(allAid);
	_username = encodeURIComponent(b64.encode(username));
	_password = encodeURIComponent(password);
	
	var RequestUrl = apiHost + '&ac=addthread&subject='+_subject+'&message='+_message+'&ctype='+_ctype+'&fid='+fid+'&imgaid='+_imgaid+'&uid='+uid+'&username='+_username+'&password='+_password+'&region='+_region;
	
	xmlHttp(RequestUrl,addThreadCallBack);
}

/**
 * 帖子发布的回调函数
 * @param {Object} data
 */
function addThreadCallBack(data){
	
	uexWindow.closeToast();
	var returnInfo = data.info;
	if(parseInt(returnInfo) > 10000){
		uexWindow.toast("0","5","帖子发布成功,页面即将跳转…","2000");
		localStorage.setItem('tid',returnInfo);
		uexWindow.evaluatePopoverScript("threadWindow","content","showNewThread()");
		var fid = getLocalStorge('fid');
		uexWindow.evaluatePopoverScript("forum_list","content","getForumList("+fid+")");
		setTimeout(function () {
			uexWindow.close(-1);
		}, 2000);
	}else if(returnInfo == '403'){
		uexWindow.toast("0","5","发布失败，用户名或密码错误…","2000");
	}else if(returnInfo == '405'){
		uexWindow.toast("0","5","发布失败，您的用户组无权发帖…","2000");
	}else if(returnInfo == '406'){
		uexWindow.toast("0","5","发布失败，缺少发帖参数…","2000");
	}else{
		uexWindow.toast("0","5","发布失败，请稍后重试…","2000");
	}
}

/**
 * 打开帖子
 * @param {Object} tid
 */
function goThreadWindow(tid){
	if(tid == ''){
		uexWindow.alert("ERROR","未指定帖子ID,无法加载帖子内容！","返回");
	}else{
		localStorage.setItem("tid",tid);
		var threadUrl = "viewthread.html?s="+getTime();
		uexWindow.open("threadWindow",0,threadUrl,2,"","",4);
	}
}

/**
 * 帖子详情的请求函数
 */
function showThread(){
	uexWindow.toast("1","5","数据加载中…","0");
	var tid = localStorage.getItem("tid");
	
	if(tid == ''){
		uexWindow.alert("ERROR","未指定帖子ID,无法加载帖子内容！","返回");
		uexWindow.close(-1);
	}else{
		var url = apiHost + '&ac=viewthread&tid='+tid;
		xmlHttp(url,parseThread);
	}
}

/**
 * 为图片附件的最新上传的图片追加附件ID
 * @param {Object} aid
 */
function givePicAid(aid){
	$(".thumbPic").last().attr('title',aid);
}

/**
 * 取消上传出错的图片
 */
function removeErrorPic(){
	$('.docancel').last().remove();
}

/**
 * 取消指定图片
 * @param {Object} objclass
 */
function cancelPic(objclass){
	$(objclass).remove();
}

/**
 * 显示进度信息
 * @param {Object} obj
 * @param {Object} status
 */
function showLoading(obj,status){
	if(status == 1){
		$("#loadingPic").hide();
	}else{
		$("#loadingPic").show();
	}
	$('#loadingWord').html(obj);
	$('.uploading').show();
}


function uexWidgetOneCbError(opCode, errorCode, errorInfo){
	alert("errorCode:" + errorCode + "\nerrorInfo:" + errorInfo);
	showLoading("上传失败……",1);
}

/**
 * 获取GPS的回调函数
 * @param {Object} inLatitude
 * @param {Object} inLongitude
 */
function locationRequestCallBack(inLatitude,inLongitude){
	uexWindow.toast("1","5","开始获取您的位置…","0");
	uexLocation.closeLocation();
	lat = inLatitude;
	lon = inLongitude;
	
	uexLocation.getAddress(lat,lon);
}

/**
 * 坐标转换为地址的监控函数
 * @param {Object} opId
 * @param {Object} dataType
 * @param {Object} data
 */
function getAddressCallBack(opId,dataType,data){
	if(dataType == 0){
		$('#region').html(data);
		$('.region').show();
		showLoading('提示：再次点击坐标图片，可清除地址！',1);
		uexWindow.closeToast();
		uexWindow.toast("0","5","获取成功…","2000");
	}else{
		uexWindow.closeToast();
		uexWindow.toast("0","5","获取失败…","2000");
	}
}

/**
 * 打开地理位置获取API
 */
function getLocation(){
	var locationType = getLocalStorge('locationType');
	if(locationType == 'pressed'){
		removeRigion();
		localStorage.setItem('locationType','');
	}else{
		$('.regions img').attr('src','css/images/location_pressed.png');
		localStorage.setItem('locationType','pressed');
		uexLocation.openLocation()
	}
	
}

/**
 * 取消地理位置信息
 */
function removeRigion(){
	$('#region').html('');
	$('.regions img').attr('src','css/images/region.png');
	$('.region').hide();
	$('.uploading').hide();
	$('#loadingPic').show();
	$('#loadingWord').text('');
}

/**
 * 获取板块分类
 */
function getForumType(){
	var fid = getLocalStorge('fid');
	if(fid){
		var requestUrl = apiHost + '&ac=ftype&fid='+fid;
		xmlHttp(requestUrl,showType);
	}else{
		alert("板块ID丢失，请重新进入板块发帖!");
	}
}

/**
 * 显示板块分类
 * @param {Object} items
 */
function showType(items){
	var selectObj = $('#ctype');
	var j = 0;
	for(var i in items){
		j = j + 1;
		item = items[i];
		var option = '';
		option = '<option value="'+item.typeid+'">'+b64.decode(item.typename)+'</option>';
		selectObj.append(option);
	}
	
	if(j == 0){
		var option = '';
		option = '<option value="">暂无分类</option>';
		selectObj.append(option);
	}
}

function getLocalStorge(key){
	var item = localStorage.getItem(key);
	if(item=='' || item==null || typeof(item)=="undefined"){
		return false;
	}else{
		return item;
	}
}

//获取当前时间的毫秒数
//放于url请求中，避免缓存
function getTime(){
	var dateNow = new Date();
	return dateNow.getTime();
}
 